package org.grottarossa.ui.core.actions;

import java.util.ArrayList;

import com.vaadin.event.Action;

/**
 * Espone a Vaadin un insieme di {@link CustomAction} come {@link Action.Handler} Vaadin
 * @author 
 */
public class CustomActionHandlerForContextMenu implements Action.Handler
{
	private static final long serialVersionUID = 1L;

	private final ArrayList<CustomAction> m_commands;
	private final boolean hideDisabledActions;

	/**
	 * @param hideDisabledActions true per nascondere le {@link CustomAction} quando sono {@link CustomAction#isEnabled(Object) inattive}
	 * @param commands {@link CustomAction} da esporre
	 */
	public CustomActionHandlerForContextMenu(boolean hideDisabledActions, ArrayList<CustomAction> commands)
	{
		this.hideDisabledActions = hideDisabledActions;
		m_commands = new ArrayList<CustomAction>();

		for(CustomAction c : commands)
		{
			m_commands.add(c);
		}
	}

	public Action[] getActions(Object target, Object sender)
	{
		ArrayList<CustomAction> result = new ArrayList<CustomAction>();
		for (CustomAction c: m_commands)
		{
			if (!hideDisabledActions || c.isEnabled(target))
				result.add(c);
		}

		return (Action[]) result.toArray(new Action[result.size()]);
	}

	public void handleAction(Action action, Object sender, Object target)
	{
		CustomAction c = (CustomAction)action;

		c.run(target);
	}

}
